package admin.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.CoordinaModel;
import models.DeliveryModel;
import models.OrderModel;
import models.OrderProductModel;
import models.RouteModel;
import models.StaffModel;
import admin.data.CoordinaData;
import admin.data.DeliveryData;
import admin.data.RouteData;
import admin.data.StaffData;
import data.OrderData;

@SuppressWarnings("serial")
public class AccountingCoordinaServlet extends HttpServlet {
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		TimeZone localTimeZone = TimeZone.getTimeZone("GMT+07:00");
		TimeZone.setDefault(localTimeZone);
		Calendar.getInstance().setTimeZone(localTimeZone);
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = path.replaceAll("/admin/coordina/accounting/", "");
		ArrayList<CoordinaModel> listCoordina = new ArrayList<CoordinaModel>();
		if (params.length() > 8) {
			CoordinaData coordinaData = new CoordinaData();
			CoordinaModel coordinaModel = coordinaData.getById(params);
			if ((coordinaModel == null) || (coordinaModel.getStatus() != 4)) {
				HttpSession session = request.getSession();
				session.setAttribute("alert",
						"Mã tuyến sai hoặc tuyến đã thu tiền !");

				response.sendRedirect("/admin/coordina/accounting/");
			} else {
				StaffData staffData = new StaffData();
				StaffModel staff = staffData.getByCode(coordinaModel
						.getEmployeeId());
				String[] listOrderId = coordinaModel.getListOrder().split(",");
				TreeMap<String, OrderProductModel> mapOrderProduct = new TreeMap<String, OrderProductModel>();
				TreeMap<String, Integer> mapProductReturn = new TreeMap<String, Integer>();
				int totalVC = 0;
				int totalSP = 0;
				for (int i = 0; i < listOrderId.length; i++) {
					if (listOrderId[i].length() > 9) {
						OrderModel orderModel = OrderData
								.getOrder(listOrderId[i]);
						TreeMap<String, Integer> productReturn = OrderData
								.getProductReturn(orderModel
										.getReturnCoordina());
						List<String> listOrderProduct = orderModel
								.getListOrderProduct();
						for (String stringOrderProduct : listOrderProduct) {
							OrderProductModel orderProduct = new OrderProductModel();
							orderProduct.getValueFromString(stringOrderProduct);
							if (mapOrderProduct.containsKey(orderProduct
									.getProductId())) {
								int quantity = mapOrderProduct.get(
										orderProduct.getProductId())
										.getQuantity()
										+ orderProduct.getQuantity();
								orderProduct.setStoreType(orderModel
										.getDealProductType());
								orderProduct.setQuantity(quantity);
							} else {
								orderProduct.setStoreType(orderModel
										.getDealProductType());
								if (orderModel.getDealProductType() == 0) {
									totalVC++;
								}
								if (orderModel.getDealProductType() == 1) {
									totalSP++;
								}
							}
							orderProduct
									.setUnitPrice(orderModel.getUnitPrice());
							orderProduct.setCheckOut(orderModel.isCheckOut());
							mapOrderProduct.put(orderProduct.getProductId(),
									orderProduct);
						}

						for (Map.Entry<String, Integer> entry : productReturn
								.entrySet()) {
							if (mapProductReturn.containsKey(entry.getKey())) {
								mapProductReturn.put(
										entry.getKey(),
										entry.getValue()
												+ mapProductReturn.get(entry
														.getKey()));
							} else {
								mapProductReturn.put(entry.getKey(),
										entry.getValue());
							}
						}
					}
				}

				for (Map.Entry<String, Integer> entry : mapProductReturn
						.entrySet()) {
					if (mapOrderProduct.containsKey(entry.getKey())) {
						int productDelivered = mapOrderProduct.get(
								entry.getKey()).getQuantity()
								- mapProductReturn.get(entry.getKey());
						mapOrderProduct.get(entry.getKey()).setProductReturn(
								mapProductReturn.get(entry.getKey()));
						mapOrderProduct.get(entry.getKey())
								.setProductDelivered(productDelivered);
					}
				}

				try {
					Cache cache = CacheManager.getInstance().getCacheFactory()
							.createCache(Collections.emptyMap());
					cache.put("mapOrderProduct/" + coordinaModel.getId(),
							mapOrderProduct);
				} catch (CacheException e) {

				}

				request.setAttribute("coordinaModel", coordinaModel);
				request.setAttribute("staff", staff);
				request.setAttribute("mapOrderProduct", mapOrderProduct);
				request.setAttribute("mapProductReturn", mapProductReturn);
				request.setAttribute("totalVC", totalVC);
				request.setAttribute("totalSP", totalSP);
				try {
					request.getRequestDispatcher(
							"/admin/pages/accounting_coordina.jsp").forward(
							request, response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			CoordinaData coordinaData = new CoordinaData();
			listCoordina = coordinaData.getCoordina("", "4", "", "", "", "");
			RouteData routeData = new RouteData();
			TreeMap<String, RouteModel> mapRoute = routeData.getMapRoute();
			request.setAttribute("mapRoute", mapRoute);
			request.setAttribute("listCoordina", listCoordina);
			try {
				request.getRequestDispatcher(
						"/admin/pages/accounting_coordina_list.jsp").forward(
						request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String action = (String) request.getParameter("action");
		String coordinaId = (String) request.getParameter("coordinaId");

		if (action.equalsIgnoreCase("search")) {
			response.sendRedirect("/admin/coordina/accounting/" + coordinaId);
		}
		if (action.equalsIgnoreCase("saveAccounting")) {
			CoordinaModel coordinaModel = new CoordinaModel();
			CoordinaData coordinaData = new CoordinaData();
			coordinaModel = coordinaData.getById(coordinaId);
			coordinaModel.setStatus(5);
			coordinaModel.setCreated(new Date());
			coordinaData.insert(coordinaModel);

			String[] listOrderId = coordinaModel.getListOrder().split(",");
			TreeMap<String, Integer> mapAddress = new TreeMap<String, Integer>();
			int order = 0;
			for (int i = 0; i < listOrderId.length; i++) {
				if (listOrderId[i].length() > 9) {
					OrderModel orderModel = new OrderModel();
					orderModel = OrderData.getOrder(listOrderId[i]);
					if (orderModel.getStatus() == 4) {
						order++;
						mapAddress.put(orderModel.getShipAddressFull(), 1);
						if (!orderModel.isCheckOut()) {
							orderModel.setCheckOut(true);
							orderModel.setCheckOutTime(Calendar.getInstance()
									.getTime());
							OrderData.insert(orderModel);
						}
					}
				}
			}
			int address = mapAddress.size();

			StaffModel staffModel = new StaffModel();
			StaffData staffData = new StaffData();
			staffModel = staffData.getByCode(coordinaModel.getEmployeeId());

			DeliveryData deliveryData = new DeliveryData();
			DeliveryModel deliveryModel = new DeliveryModel();
			deliveryModel.setId(coordinaModel.getId());
			deliveryModel.setOrder(order);
			deliveryModel.setAddress(address);
			deliveryModel.setEmployeeId(staffModel.getCode());
			deliveryModel.setEmployeeName(staffModel.getName());
			deliveryModel.setCreated(new Date());
			deliveryData.insert(deliveryModel);

			HttpSession session = request.getSession();
			session.setAttribute("success", "Kế toán thu tiền thành công !");
			response.sendRedirect("/admin/coordina/accounting/");
		}
	}
}